<template>
    <div class="layout">
        <Header v-if="tableTotal" />
        <div class="container">
            <ZWGroup
                ref="GroupingRef"
                :type="28"
                :group-id="group_id"
                :get-group-fun="handleGetGroupList"
                @submit="handleGroupSubmit" />
            <div class="container_right">
                <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" />
                <ZwTable
                    ref="tableRef"
                    class="table-box"
                    tab-h="initial"
                    :option="tableOption"
                    :fetch-params="state.searchParams"
                    :row-key="getRowKey"
                    :fetch-api="fetchApi()"
                    :close-loading="true"
                    @select="onSelect"
                    @selection-change="onSelectionChange"
                    @select-all="onSelectAll">
                    <template #headerOperate>
                        <!-- <el-button v-auth="'BATCH_DOWN_LOAD'" plain @click="onChange(3)" :disabled="checkList.length == 0">批量下载</el-button>
            <el-button v-auth="'BATCH_DEL'" plain @click="onChange(0)" :disabled="checkList.length == 0">批量删除</el-button>
            <el-button v-auth="'ADD'" type="primary" @click="toCreateActivity">新建活动</el-button> -->
                        <el-dropdown class="dropdown_btn" @command="onBatch">
                            <el-button plain :disabled="!checkList.length">
                                批量操作
                                <el-icon class="el-icon--right"><arrow-down /> </el-icon>
                            </el-button>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item v-auth="'BATCH_BEGIN'" command="begins">
                                        批量开始
                                    </el-dropdown-item>
                                    <el-dropdown-item v-auth="'BATCH_END'" command="ends"> 批量结束 </el-dropdown-item>
                                    <el-dropdown-item v-auth="'BATCH_DOWNLOAD'" command="downloads">
                                        批量下载
                                    </el-dropdown-item>
                                    <el-dropdown-item v-auth="'BATCH_DEL'" command="dels"> 批量删除</el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                        <div style="margin-left: 10px">
                            <el-button type="primary" @click="onCreateRoute">新建活动</el-button>
                        </div>
                    </template>
                </ZwTable>
            </div>
        </div>
    </div>
    <!-- 删除弹框 -->
    <ZWDeletdialog ref="DeletdialogRef" @submit="onSubmit" />
</template>

<script lang="tsx">
import { defineComponent } from 'vue';
// 定义name专用script标签
// eslint-disable-next-line vue/component-definition-name-casing
export default defineComponent({ name: 'CUSTOMER_GROUP_MANAGE_UNLIMITEDPULL' });
</script>

<script setup lang="tsx">
import Header from './components/Header.vue';
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import ZWDeletdialog from '@/components/ZWDeletdialog.vue';
import ZWGroup from '@/components/ZWGroup.vue';
import useClipboard from 'vue-clipboard3';
import { ElMessage, ElImage, ElIcon, ElButton } from 'element-plus';
import { Picture as IconPicture } from '@element-plus/icons-vue';
import { getGroupList } from '@/api/concreation';
import {
    getUnlimitedPullList,
    downloadUnlimitedPull,
    startUnlimitedPull,
    stopUnlimitedPull,
    delUnlimitedPull
} from '@/api/customer/groupManage/unlimitedPull';
import { endLoading, startLoading } from '@/utils/request';
import { ref, reactive, computed, onActivated, onMounted } from 'vue';

import { useStore } from '@/store';
import { useRouter, useRoute } from 'vue-router';
import { deepCopy } from '@/utils/helper';
import { StatusColor, DOWLOAD_FILE } from '@/utils/smartMarketing';
import { getCreateList } from '@/api/common';
import { isCachePage } from '@/utils/utils';

const DeletdialogRef: any = ref(null);
const router = useRouter();
const route = useRoute();
const store = useStore();
const GroupingRef: any = ref(null);
const checkList = ref([]);
const delId = ref('');

const requestFlag = ref<boolean>(false);
const currentParams = ref<any>(null);
const group_id = ref<string | number>('all');

const defaultParams = {
    group_id: 'all', //分组ID
    name: '', //群裂变名称
    work_user_id: [], //创建人
    activity_time: [], //活动有效期
    activity_status: 0 //活动状态
};
const tableTotal = ref(false);

// // 分组权限code码
// const authCode = {
//   add: 'ADD_CHILD_GROUP',
//   edit: 'EDIT_CHILD_GROUP',
//   del: 'DEL_CHILD_GROUP'
// }
// 二次包装处理分组接口方法，拿取总数判断头部是否显示
const handleGetGroupList = async (data: any) => {
    const res = await getGroupList(data);
    tableTotal.value = res.total == 0 ? true : false;
    return res;
};

// 复制
const { toClipboard } = useClipboard();
const onCopy = async (v: any) => {
    try {
        await toClipboard(v);
        ElMessage.success('复制成功');
    } catch (e) {
        ElMessage.error('复制失败');
    }
};

const handleGroupSubmit = (v: any) => {
    // 解决切换分组，点击新增然后取消之后的默认分组问题 ⬇️
    router.push({ path: '/customer/groupManage/unlimitedPull', query: { group_id: v.id } });
    group_id.value = v.id;
    currentParams.value = { ...deepCopy(defaultParams), ...currentParams.value, group_id: group_id.value };
    state.searchParams = deepCopy(currentParams.value);
    tableRef.value?.clearSelection();
};

const tableRef: any = ref<HTMLElement | null>(null);

const state = reactive({
    searchParams: deepCopy(defaultParams),
    searchHeight: '112px'
});
const searchOption = computed(() => {
    return [
        {
            label: '活动搜索',
            name: 'name',
            value: '',
            type: 'input',
            placeholder: '请输入活动标题进行搜索'
        },
        {
            label: '创建人',
            name: 'work_user_id',
            value: [],
            multiple: true,
            type: 'select',
            filterable: true,
            placeholder: '请选择创建人',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getCreateList({}).then((res: any) => {
                        const targetArr = res.map((item: any) => {
                            item.name = `${item.name}  (${item.phone}) `;
                            return item;
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '活动状态',
            name: 'activity_status',
            value: '',
            type: 'select',
            placeholder: '请选择',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    resolve([
                        { name: '全部', id: 0 },
                        { name: '未开始', id: 1 },
                        { name: '进行中', id: 2 },
                        { name: '已结束', id: 3 },
                        { name: '提前结束', id: 4 }
                    ]);
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '活动有效期',
            name: 'activity_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            defaultTime: [new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)],
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        }
    ];
});
const search = (v: any) => {
    tableRef.value?.clearSelection();
    currentParams.value = { ...deepCopy(defaultParams), ...v, group_id: group_id.value };
    state.searchParams = deepCopy(currentParams.value);
};
const reset = (v: any) => {
    tableRef.value?.clearSelection();
    currentParams.value = { ...deepCopy(defaultParams), group_id: group_id.value };
    state.searchParams = deepCopy(currentParams.value);
};

const onBtn = (row: any) => {
    const BEGIN = (
        <ElButton
            size="small"
            v-auth="BEGIN"
            onClick={() => {
                isType.value = 'begin';
                delId.value = row.id;
                DeletdialogRef.value.appDialog.title = '开始';
                DeletdialogRef.value.content = '确定开始所选活动吗？';
                DeletdialogRef.value.appDialog.visible = true;
            }}>
            开始
        </ElButton>
    );
    const END = (
        <ElButton
            size="small"
            v-auth="END"
            onClick={() => {
                isType.value = 'end';
                delId.value = row.id;
                DeletdialogRef.value.appDialog.title = '结束';
                DeletdialogRef.value.content = '确定结束所选活动吗？';
                DeletdialogRef.value.appDialog.visible = true;
            }}>
            结束
        </ElButton>
    );
    const LOOK = (
        <ElButton
            size="small"
            v-auth="LOOK"
            onClick={() => {
                router.push({
                    path: '/customer/groupManage/unlimitedPull/detail',
                    query: { type: 'look', id: row.id }
                });
            }}>
            查看
        </ElButton>
    );
    const STATISTICS = (
        <ElButton
            size="small"
            v-auth="STATISTICS"
            onClick={() => {
                router.push({ path: '/customer/groupManage/unlimitedPull/statistics', query: { id: row.id } });
            }}>
            统计
        </ElButton>
    );
    const EDIT = (
        <ElButton
            size="small"
            v-auth="EDIT"
            onClick={() => {
                router.push({
                    path: '/customer/groupManage/unlimitedPull/detail',
                    query: { type: 'edit', id: row.id }
                });
            }}>
            编辑
        </ElButton>
    );
    const DEL = (
        <ElButton
            size="small"
            v-auth="DEL"
            onClick={() => {
                isType.value = 'del';
                delId.value = row.id;
                DeletdialogRef.value.appDialog.title = '删除';
                DeletdialogRef.value.content = '确定删除所选活动吗？';
                DeletdialogRef.value.appDialog.visible = true;
            }}>
            删除
        </ElButton>
    );
    const DOWNLOAD = (
        <ElButton
            size="small"
            v-auth="DOWNLOAD"
            onClick={() => {
                onDownload(row);
            }}>
            下载
        </ElButton>
    );
    const COPY = (
        <ElButton
            size="small"
            v-auth="COPY"
            onClick={() => {
                onCopy(row.activity_url);
            }}>
            复制
        </ElButton>
    );
    switch (row.status) {
        case 1:
            return [LOOK, EDIT, BEGIN, COPY, DOWNLOAD, DEL];
        case 2:
            return [LOOK, END, COPY, DOWNLOAD, STATISTICS, DEL];
        case 3:
        case 4:
            return [LOOK, STATISTICS, DEL];
    }
};
// 表格
const tableOption = [
    {
        type: 'selection',
        width: 55,
        fixed: 'left',
        reserveSelection: true
    },
    {
        prop: 'title',
        label: '标题',
        minWidth: 200
    },
    {
        prop: 'qr_code_link',
        label: '二维码',
        align: 'center',
        minWidth: 100,
        render({ row, column, index }) {
            const slotError = () => (
                <div class="image-slot">
                    <ElIcon>
                        <IconPicture />
                    </ElIcon>
                </div>
            );
            return (
                <>
                    <ElImage
                        preview-src-list={[row.groupchat_qr_code]}
                        preview-teleported={true}
                        src={row.groupchat_qr_code}
                        style="width: 48px; height: 48px; font-size: 49px"
                        vSlots={{ error: slotError }}
                    />
                </>
            );
        }
    },
    {
        prop: 'member_join_nums',
        label: '净增人数',
        align: 'center',
        width: 100
    },
    {
        prop: 'fission_num',
        label: '裂变群数',
        align: 'center',
        width: 150
    },
    {
        prop: 'group_name',
        label: '所属分组',
        width: 200
    },
    {
        prop: 'created_user_name',
        label: '创建人',
        width: 200
    },
    {
        prop: 'activity_time',
        label: '活动有效期',
        width: 200,
        render({ row, column, index }) {
            return (
                <>
                    {row.period_type == 1 ? (
                        '永久'
                    ) : (
                        <div>
                            <p>{row.activity_time[0]}</p>
                            <p>至</p>
                            <p>{row.activity_time[1]}</p>
                        </div>
                    )}
                </>
            );
        }
    },
    {
        prop: 'status',
        label: '状态',
        width: 100,
        align: 'center',
        render({ row, column, index }) {
            return <span style={StatusColor(row.status, 'obj')?.color}>{StatusColor(row.status, 'obj')?.name}</span>;
        }
    },
    {
        prop: 'operate',
        label: '操作',
        width: 295,
        fixed: 'right',
        isOperate: true,
        renderOperate({ row }) {
            return onBtn(row);
        }
    }
];
const fetchApi = () => {
    return getUnlimitedPullList;
};
const getRowKey = (row: any) => {
    return row.id;
};
// 选中表格 checkbox
const onSelect = (selection, row) => {
    if (selection.constructor === Array) checkList.value = selection.map(v => v.id);
};
// 选择项变更
const onSelectionChange = selection => {};
// 全选
const onSelectAll = selection => {
    checkList.value = selection.map(v => v.id);
};
// 刷新表格
const reloadTable = () => {
    tableRef.value.reload();
};
const onDownload = (row: any) => {
    DOWLOAD_FILE(row.groupchat_qr_code, row.title);
};
const isType = ref<string>('');
const onBatch = (type: string) => {
    isType.value = type;
    switch (type) {
        case 'dels':
            DeletdialogRef.value.appDialog.title = '删除';
            DeletdialogRef.value.content = '确定删除所选活动吗？';
            break;
        case 'downloads':
            downloadUnlimitedPull({ id: checkList.value }).then((res: any) => {
                DOWLOAD_FILE(res.url, res.file_name);
                tableRef.value?.clearSelection();
            });
            break;
        case 'begin':
            DeletdialogRef.value.appDialog.title = '开始';
            DeletdialogRef.value.content = '确定开启所选活动吗？';
            break;
        case 'begins':
            DeletdialogRef.value.appDialog.title = '批量开启';
            DeletdialogRef.value.content = '确定开启所选活动吗？';
            break;
        case 'end':
            DeletdialogRef.value.appDialog.title = '结束';
            DeletdialogRef.value.content = '确定结束所选活动吗？';
            break;
        case 'ends':
            DeletdialogRef.value.appDialog.title = '批量结束';
            DeletdialogRef.value.content = '确定结束所选活动吗？';
            break;
    }
    if (type != 'downloads') {
        DeletdialogRef.value.appDialog.visible = true;
    }
};
const onSubmit = async () => {
    startLoading();
    try {
        switch (isType.value) {
            case 'del':
                await delUnlimitedPull({ id: [delId.value] });
                GroupingRef.value.getGroup(28);
                reloadTable();
                checkList.value = [];
                ElMessage.success('删除成功');
                tableRef.value?.clearSelection();
                break;
            case 'dels':
                await delUnlimitedPull({ id: checkList.value });
                GroupingRef.value.getGroup(28);
                reloadTable();
                checkList.value = [];
                ElMessage.success('批量删除成功');
                tableRef.value?.clearSelection();
                break;
            case 'begin':
                await startUnlimitedPull({ id: [delId.value] });
                reloadTable();
                checkList.value = [];
                ElMessage.success('开始成功');
                tableRef.value?.clearSelection();
                break;
            case 'begins':
                await startUnlimitedPull({ id: checkList.value });
                reloadTable();
                checkList.value = [];
                ElMessage.success('批量开始成功');
                tableRef.value?.clearSelection();
                break;
            case 'end':
                await stopUnlimitedPull({ id: [delId.value] });
                reloadTable();
                checkList.value = [];
                ElMessage.success('结束成功');
                tableRef.value?.clearSelection();
                break;
            case 'ends':
                await stopUnlimitedPull({ id: checkList.value });
                reloadTable();
                checkList.value = [];
                ElMessage.success('批量结束成功');
                tableRef.value?.clearSelection();
                break;
        }
    } catch (error) {
        endLoading();
    }
};

// 新增抽奖活动
const onCreateRoute = () => {
    router.push({
        path: '/customer/groupManage/unlimitedPull/detail',
        query: { group_id: group_id.value == 'all' ? '0' : group_id.value }
    });
};

onActivated(async (val: any) => {
    const groupId = Number(route.params?.group_id || route.query?.group_id);
    if (isCachePage() || groupId || groupId == 0) {
        if ((groupId || groupId == 0) && group_id.value != groupId) {
            group_id.value = groupId;
        } else {
            await GroupingRef.value.getGroup(28);
        }
        await GroupingRef.value.setCurrentSelectId({ id: group_id.value });
        tableRef.value?.clearSelection();
        state.searchParams = {
            ...deepCopy(defaultParams),
            ...currentParams.value,
            group_id: groupId || group_id.value
        };
    }
});
</script>

<style lang="scss" scoped>
.layout {
    height: calc(100vh - 142px);
    display: flex;
    flex-direction: column;

    .container {
        flex: 1;
        display: flex;
        overflow: hidden;

        .container_right {
            padding: 24px;
            border: 1px solid #eaeaea;
            border-radius: 4px;
            box-sizing: border-box;
            background-color: #fff;
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;

            .zw-table {
                display: flex;
                flex-direction: column;
                flex: 1;
                overflow: hidden;

                :deep(.el-table) {
                    flex: 1;

                    .el-table__empty-block {
                        position: absolute;
                        top: 50%;
                        left: 50%;
                        transform: translate(-50%, -50%);
                    }
                }
            }
        }
    }
}
</style>
